"""Basic framework handling csv io and html page generation"""
import matplotlib
matplotlib.use('Agg')
import urllib
import csv
from question4 import Question4
from matplotlib.figure import Figure
class Framework:
    def __init__(self):
        # open csv files
        tmp = open("moviestats_boxoffice.csv",'r')
        self.small_dataset = csv.reader(tmp)
        tmp = open("moviestats_large.csv",'r')
        self.large_dataset = csv.reader(tmp)

        # separate header from dataset, assign to var
        self.small_header = self.small_dataset.next()
        self.large_header = self.large_dataset.next()
        # convert into a py list
        self.small_dataset = list(self.small_dataset)
        self.large_dataset = list(self.large_dataset)

    def to_html(self, title):
        body = ''
        #make a new question object for each q, put them in a list
        questions = [Question4(self)]
        imgcount = 0
        for q in questions:
            res = q.get_result()#run each question
            for r in res: #generate output
                if type(r) is str:
                    body+=r+'<br/>\n'
                elif r.__class__ is Figure: # I gave up on doing this with type(), this works fine
                    r.savefig('plot%d.png'%imgcount)
                    body+='<img src="plot%d.png" alt="plot%d"/>\n'%(imgcount,imgcount)
                    imgcount+=1
                else:
                    raise ValueError, 'Either string or Figure required as return value'
            """ input a title and body to be printed in html"""
            print 'Content-Type: text/html\n'
            print """
                        <html>
                            <head> <title> %s </title>
                            </head>
                            <body> %s
                            </body>
                        </html>
                  """ % (title, body)

# main
f = Framework()
f.to_html('Title')
